
<template>
  <div class="task-manager">
    <div v-for="(task, index) in tasks" :key="task.id" class="task-card">
      <h3>{{ task.name }}</h3>
      <p>间隔: {{ task.interval }}秒</p>
      <p>状态: {{ task.active ? '运行中' : '已停止' }}</p>
      <p>下次执行: {{ formatTime(task.nextRun) }}</p>
      <button @click="toggleTask(index)">
        {{ task.active ? '停止' : '启动' }}
      </button>
    </div>
    <div class="add-task">
      <input v-model="newTask.name" placeholder="任务名称">
      <input v-model.number="newTask.interval" type="number" placeholder="间隔(秒)">
      <button @click="addTask">添加任务</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

const tasks = ref([])
const timers = ref({})
const newTask = ref({ name: '', interval: 60 })

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

const executeTask = async (taskId) => {
  try {
    const response = await axios.post('/execute-task', { taskId })
    console.log('任务执行结果:', response.data)
  } catch (error) {
    console.error('任务执行失败:', error)
  }
}

const startTask = (index) => {
  const task = tasks.value[index]
  task.active = true
  task.nextRun = Date.now() + task.interval * 1000
  
  timers.value[task.id] = setInterval(() => {
    executeTask(task.id)
    task.nextRun = Date.now() + task.interval * 1000
  }, task.interval * 1000)
}

const stopTask = (index) => {
  const task = tasks.value[index]
  task.active = false
  clearInterval(timers.value[task.id])
  delete timers.value[task.id]
}

const toggleTask = (index) => {
  tasks.value[index].active ? stopTask(index) : startTask(index)
}

const addTask = () => {
  if (!newTask.value.name || !newTask.value.interval) return
  
  const task = {
    id: Date.now(),
    name: newTask.value.name,
    interval: newTask.value.interval,
    active: false,
    nextRun: 0
  }
  
  tasks.value.push(task)
  newTask.value = { name: '', interval: 60 }
}

onMounted(async () => {
  const response = await axios.get('/tasks')
  tasks.value = response.data
})

onUnmounted(() => {
  Object.values(timers.value).forEach(clearInterval)
})
</script>

<style scoped>
.task-manager {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}
.task-card {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
